<?php
$SandboxFlag = true;
if ($SandboxFlag == true) 
{
		$API_Endpoint = "https://api-3t.sandbox.paypal.com/nvp";
		$PAYPAL_URL = "https://www.sandbox.paypal.com/webscr?cmd=_express-checkout&token=";
}
else
{
		$API_Endpoint = "https://api-3t.paypal.com/nvp";
		$PAYPAL_URL = "https://www.paypal.com/cgi-bin/webscr?cmd=_express-checkout&token=";
}

function CallShortcutExpressCheckout( $paymentAmount, $currencyCodeType, $paymentType, $returnURL, $cancelURL,$arregloItem,$shipToName,$shipToStreet,$shipToStreet2,$shipToCity,$shipToState,$shipToCountryCode,$shipToZip,$phoneNum,$INVNUM,$CUSTOM,$sw) 
{
        //------------------------------------------------------------------------------------------------------------------------------------
        // Construct the parameter string that describes the SetExpressCheckout API call in the shortcut implementation

    
        $nvpstr="&PAYMENTREQUEST_0_AMT=". $paymentAmount;
        $nvpstr = $nvpstr . "&PAYMENTREQUEST_0_PAYMENTACTION=" . $paymentType;
        $nvpstr = $nvpstr . "&RETURNURL=" . $returnURL;
        $nvpstr = $nvpstr . "&CANCELURL=" . $cancelURL;

        $nvpstr = $nvpstr .$arregloItem;
        $nvpstr = $nvpstr . "&PAYMENTREQUEST_0_CURRENCYCODE=" . $currencyCodeType;		

        $nvpstr = $nvpstr . "&PAYMENTREQUEST_0_INVNUM=".$INVNUM;
        $nvpstr = $nvpstr . "&PAYMENTREQUEST_0_CUSTOM=".$CUSTOM;
        
        
        if($sw==1)
        {
            $nvpstr = $nvpstr . "&ADDROVERRIDE=1";
            $nvpstr = $nvpstr . "&PAYMENTREQUEST_0_SHIPTONAME=" . $shipToName;
            $nvpstr = $nvpstr . "&PAYMENTREQUEST_0_SHIPTOSTREET=" . $shipToStreet;
            $nvpstr = $nvpstr . "&PAYMENTREQUEST_0_SHIPTOSTREET2=" . $shipToStreet2;
            $nvpstr = $nvpstr . "&PAYMENTREQUEST_0_SHIPTOCITY=" . $shipToCity;
            $nvpstr = $nvpstr . "&PAYMENTREQUEST_0_SHIPTOSTATE=" . $shipToState;
            $nvpstr = $nvpstr . "&PAYMENTREQUEST_0_SHIPTOCOUNTRYCODE=" . $shipToCountryCode;
            $nvpstr = $nvpstr . "&PAYMENTREQUEST_0_SHIPTOZIP=" . $shipToZip;
        }
        

        $_SESSION["currencyCodeType"] = $currencyCodeType;	  
        $_SESSION["PaymentType"] = $paymentType;

        //'--------------------------------------------------------------------------------------------------------------- 
        //' Make the API call to PayPal
        //' If the API call succeded, then redirect the buyer to PayPal to begin to authorize payment.  
        //' If an error occured, show the resulting errors
        //'---------------------------------------------------------------------------------------------------------------
        $resArray=hash_call("SetExpressCheckout", $nvpstr);
        
        
        $ack = strtoupper($resArray["ACK"]);
        if($ack=="SUCCESS" || $ack=="SUCCESSWITHWARNING")
        {
                $token = urldecode($resArray["TOKEN"]);
                $_SESSION['TOKEN']=$token;
        }
        return $resArray;
            
}

    
    
    function hash_call($methodName,$nvpStr)
    {
        
         /********************************************
	PayPal API Module
	********************************************/
	$PROXY_HOST = '127.0.0.1';
	$PROXY_PORT = '808';

	$SandboxFlag = true;

	$API_UserName="jmadri_1316536185_biz_api1.netosfera.com";
	$API_Password="1316536238";
	$API_Signature="AZjHJfwFTKfkGqcn9gZlj45YBNm7AV6thIp9YRin4jdfjjDGi5c0atvu ";

	// BN Code 	is only applicable for partners
	$sBNCode = "PP-ECWizard";	
	
	if ($SandboxFlag == true) 
	{
		$API_Endpoint = "https://api-3t.sandbox.paypal.com/nvp";
		$PAYPAL_URL = "https://www.sandbox.paypal.com/webscr?cmd=_express-checkout&token=";
	}
	else
	{
		$API_Endpoint = "https://api-3t.paypal.com/nvp";
		$PAYPAL_URL = "https://www.paypal.com/cgi-bin/webscr?cmd=_express-checkout&token=";
	}
        
	$USE_PROXY = false;
	$version="64";

	if (session_id() == "") 
		session_start();
		//declaring of global variables
		//global $API_Endpoint, $version, $API_UserName, $API_Password, $API_Signature;
		//global $USE_PROXY, $PROXY_HOST, $PROXY_PORT;
		//global $gv_ApiErrorURL;
		//global $sBNCode;

                
                
		//setting the curl parameters.
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL,$API_Endpoint);
		curl_setopt($ch, CURLOPT_VERBOSE, 1);

		//turning off the server and peer verification(TrustManager Concept).
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);

		curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
		curl_setopt($ch, CURLOPT_POST, 1);
		
	    //if USE_PROXY constant set to TRUE in Constants.php, then only proxy will be enabled.
	   //Set proxy name to PROXY_HOST and port number to PROXY_PORT in constants.php 
		if($USE_PROXY)
			curl_setopt ($ch, CURLOPT_PROXY, $PROXY_HOST. ":" . $PROXY_PORT); 

		//NVPRequest for submitting to server
		$nvpreq="METHOD=" . urlencode($methodName) . "&VERSION=" . urlencode($version) . "&PWD=" . urlencode($API_Password) . "&USER=" . urlencode($API_UserName) . "&SIGNATURE=" . urlencode($API_Signature) . $nvpStr . "&BUTTONSOURCE=" . urlencode($sBNCode);

		//setting the nvpreq as POST FIELD to curl
		curl_setopt($ch, CURLOPT_POSTFIELDS, $nvpreq);

		//getting response from server
		$response = curl_exec($ch);

		//convrting NVPResponse to an Associative Array
		$nvpResArray=deformatNVP($response);
		$nvpReqArray=deformatNVP($nvpreq);
		$_SESSION['nvpReqArray']=$nvpReqArray;

		if (curl_errno($ch)) 
		{
			// moving to display page to display curl errors
			  $_SESSION['curl_error_no']=curl_errno($ch) ;
			  $_SESSION['curl_error_msg']=curl_error($ch);

			  //Execute the Error handling module to display errors. 
		} 
		else 
		{
			 //closing the curl
		  	curl_close($ch);
		}

		return $nvpResArray;
	}
        
        function deformatNVP($nvpstr)
	{
		$intial=0;
	 	$nvpArray = array();

		while(strlen($nvpstr))
		{
			//postion of Key
			$keypos= strpos($nvpstr,'=');
			//position of value
			$valuepos = strpos($nvpstr,'&') ? strpos($nvpstr,'&'): strlen($nvpstr);

			/*getting the Key and Value values and storing in a Associative Array*/
			$keyval=substr($nvpstr,$intial,$keypos);
			$valval=substr($nvpstr,$keypos+1,$valuepos-$keypos-1);
			//decoding the respose
			$nvpArray[urldecode($keyval)] =urldecode( $valval);
			$nvpstr=substr($nvpstr,$valuepos+1,strlen($nvpstr));
	         }
		 return $nvpArray;
	}
        function RedirectToPayPal ( $token ,$PAYPAL_URL)
	{
		//global $PAYPAL_URL;
		// Redirect to paypal.com here
		$payPalURL = $PAYPAL_URL . $token;
                sfContext::getInstance()->getController()->redirect($payPalURL);
		//header("Location: ".$payPalURL);
                
	}
/*-----------------Fin de funciones de PayPal-------------------------*/
/*-----------------Integracion con PayPal-------------------------*/
$contador=0;
$suma=0;
$arregloItem="";
//Item de compra
  foreach($products as $product) :

    $price = $product->Product->getDiscountedPrice();
    $product_name = $product->Product->getName() ;
    $product_description = $cart_param['product_description'] ;
    $product_quantity = $product->getProductQuantity();

    $subto=$product_quantity*$price;   
    $suma=$suma+$subto;   
    $producto= $product_name;
    $descripcion= $product_description;
    $precio= $price;
    $cantidad= $product_quantity;

    $id="1";	
    $arregloItem = $arregloItem  . "&L_PAYMENTREQUEST_0_NAME$contador=$producto";
    $arregloItem = $arregloItem . "&L_PAYMENTREQUEST_0_NUMBER$contador=$id";
    $arregloItem = $arregloItem . "&L_PAYMENTREQUEST_0_DESC$contador=$descripcion";
    $arregloItem = $arregloItem . "&L_PAYMENTREQUEST_0_AMT$contador=$precio";
    $arregloItem = $arregloItem . "&L_PAYMENTREQUEST_0_QTY$contador=$cantidad";

    $contador++; 
    
  endforeach;

//Importe de la compra

    $impuesto=number_format($invoice->getTaxAmount(),2);
    $seguro="0.00";
    $envio=number_format($invoice->getShippingAmount(),2);
    $menejoEnvio="0.00";
    $descuentoEnvio="0.00";
    
    $arregloItem = $arregloItem . "&PAYMENTREQUEST_0_ITEMAMT=$suma";
    $arregloItem = $arregloItem . "&PAYMENTREQUEST_0_TAXAMT=$impuesto";
    $arregloItem = $arregloItem . "&PAYMENTREQUEST_0_SHIPPINGAMT=$envio";
    $arregloItem = $arregloItem . "&PAYMENTREQUEST_0_HANDLINGAMT=$menejoEnvio";
    $arregloItem = $arregloItem . "&PAYMENTREQUEST_0_SHIPDISCAMT=$descuentoEnvio";		
    $arregloItem = $arregloItem . "&PAYMENTREQUEST_0_INSURANCEAMT=$seguro";
    $arregloItem = $arregloItem . "&ALLOWNOTE=1";

    $_SESSION["Payment_Amount"]=$suma+$impuesto+$seguro+$envio+$menejoEnvio+$descuentoEnvio;
    $currencyCodeType = "USD";
    $paymentType = "Sale";

    $returnURL = "http://corppon.webpage.com.ve/invoices/confirmation";
    //$returnURL = "http://localhost:9093/invoices/confirmation";
   // $cancelURL = "http://localhost:9093/invoices/cancel";
    $cancelURL = "http://corppon.webpage.com.ve/invoices/cancel";
    
    $invoce=$invoice->getIdInvoice();
    $shipToName=$invoice->getShippingName()." ".$invoice->getShippingLastName();
    $shipToStreet=$invoice->getShippingAddress();
    $shipToStreet2="";
    $shipToCity=$invoice->getShippingCity();
    $shipToState=$invoice->getShippingState();
    $shipToCountryCode="US";
    $shipToZip=$invoice->getShippingZip();
    $phoneNum="0000";
    $sw=1;


$INVNUM=$invoce;
$CUSTOM=$invoce;
$paymentAmount = $_SESSION["Payment_Amount"];
$_SESSION['invoce']=$invoce;

$resArray = CallShortcutExpressCheckout ($paymentAmount, $currencyCodeType, $paymentType, $returnURL, $cancelURL,$arregloItem,$shipToName,$shipToStreet,$shipToStreet2,$shipToCity,$shipToState,$shipToCountryCode,$shipToZip,$phoneNum,$INVNUM,$CUSTOM,$sw);
$ack = strtoupper($resArray["ACK"]);
if($ack=="SUCCESS" || $ack=="SUCCESSWITHWARNING")
{
	RedirectToPayPal ( $resArray["TOKEN"],$PAYPAL_URL );
} 
else  
{
	//Display a user friendly Error on the page using any of the following error information returned by PayPal
	$ErrorCode = urldecode($resArray["L_ERRORCODE0"]);
	$ErrorShortMsg = urldecode($resArray["L_SHORTMESSAGE0"]);
	$ErrorLongMsg = urldecode($resArray["L_LONGMESSAGE0"]);
	$ErrorSeverityCode = urldecode($resArray["L_SEVERITYCODE0"]);
	
	echo "SetExpressCheckout API call failed. ";
	echo "Detailed Error Message: " . $ErrorLongMsg;
	echo "Short Error Message: " . $ErrorShortMsg;
	echo "Error Code: " . $ErrorCode;
	echo "Error Severity Code: " . $ErrorSeverityCode;
}



$sequence	= rand(1, 1000);
$timeStamp	= time();

if( phpversion() >= '5.1.2' ):
  $fingerprint = hash_hmac("md5", $loginID . "^" . $sequence . "^" . $timeStamp . "^" . $invoice_amount . "^", $transactionKey);
else :
  $fingerprint = bin2hex(mhash(MHASH_MD5, $loginID . "^" . $sequence . "^" . $timeStamp . "^" . $invoice_amount . "^", $transactionKey));
endif;


?>
<h1 style="text-align: center;">Wait...You will be redirect</h1>
<table width="720" border="0" cellspacing="0" cellpadding="0" align="center">
<form method='post' id="formCheckout" action='<?php echo $url; ?>' >
  <tr>
    <td>
      <input type=hidden name="x_type" value="auth_only"/>
      <input type='hidden' name='x_login' value='<?php echo $loginID; ?>' />
      <input type='hidden' name='x_amount' value='<?php echo $invoice->getInvoiceAmount(); ?>' />
      <input type='hidden' name='x_invoice_num' value='<?php echo $invoice->getIdInvoice(); ?>' />
      <input type='hidden' name='x_fp_sequence' value='<?php echo $sequence; ?>' />
      <input type='hidden' name='x_fp_timestamp' value='<?php echo $timeStamp; ?>' />
      <input type='hidden' name='x_fp_hash' value='<?php echo $fingerprint; ?>' />
      <input type='hidden' name='x_test_request' value='<?php echo $testMode; ?>' />
      <input type='hidden' name='x_cust_id' value='<?php echo '1'; ?>' />
      <input type='hidden' name='x_first_name' value='<?php echo $invoice->getBillingName(); ?>' />
      <input type='hidden' name='x_last_name' value='<?php echo $invoice->getBillingLastName(); ?>' />
      <input type='hidden' name='x_address' value='<?php echo $invoice->getBillingAddress(); ?>' />
      <input type='hidden' name='x_zip' value='<?php echo $invoice->getBillingZip(); ?>' />
      <input type='hidden' name='x_company' value='<?php echo $invoice->getBillingCompany(); ?>' />
      <input type='hidden' name='x_state' value='<?php echo $invoice->getBillingState(); ?>' />
      <input type='hidden' name='x_city' value='<?php echo $invoice->getBillingCity(); ?>' />
      <input type='hidden' name='x_country' value='United States' />
      <input type='hidden' name='x_phone' value='<?php echo $invoice->getBillingPhone(); ?>' />
      <input type='hidden' name='x_fax' value='<?php echo $invoice->getBillingFax(); ?>' />
      <input type='hidden' name='x_email' value='<?php echo $invoice->getBillingEmail(); ?>' />
      <input type="hidden" name="x_tax" value="Tax1<|>TX tax<|><?php echo $invoice_tax ?>"/>
      <input type="hidden" name="x_freight" value="Freight1<|> Ground <|><?php echo $shipping ?>"/>
      <!--<input type='hidden' name='x_po_num' value='<?php echo $po_num; ?>' />-->

      <!--Item de la compra-->
      
      <!--Fin item de la compra-->

      <!--Informacion de Ship-->
      <input type='hidden' name='x_ship_to_first_name' value='<?php echo $invoice->getShippingName(); ?>' />
      <input type='hidden' name='x_ship_to_last_name' value='<?php echo $invoice->getShippingLastName(); ?>' />
      <input type='hidden' name='x_ship_to_company' value='<?php echo $invoice->getShippingCompany(); ?>' />
      <input type='hidden' name='x_ship_to_address' value='<?php echo $invoice->getShippingAddress(); ?>' />
      <input type='hidden' name='x_ship_to_city' value='<?php echo $invoice->getShippingCity(); ?>' />
      <input type='hidden' name='x_ship_to_state' value='<?php echo $invoice->getShippingState(); ?>' />
      <input type='hidden' name='x_ship_to_zip' value='<?php echo $invoice->getShippingZip(); ?>' />
      <input type='hidden' name='x_ship_to_country' value='United States' />
      <!--Fin informacion de Ship-->

      <input type='hidden' name="x_relay_response" value="true">
      <input type='hidden' name="x_relay_url" value="http://corppon.webpage.com.ve/invoices/invoice"/>
      <input type='hidden' name='x_show_form' value='PAYMENT_FORM' />
      <input type="submit" name="OK" value="OK" style="display:none;"/>
    </td>
  </tr>
</form>
    
<script type="text/javascript">
function myfunc () {
//var frm = document.getElementById("formCheckout");
frm.submit();
}
window.onload = myfunc;
</script>
    
</table>